<?php
namespace app\portal\model;

use think\Db;
use think\Model;

class Article extends Model
{
    protected $autoWriteTimestamp = true;
    protected $table = 'cmf_article';

    public function adminArticleList()
    {
        $where = ['status' => 1];
        $param = request()->param(); // 获取请求信息

        $startTime = empty($param['start_time']) ? 0 : strtotime($param['start_time']);
        $endTime = empty($param['end_time']) ? 0 : strtotime($param['end_time']);

        if (!empty($param['keyword']) && $param['keyword'] !== '')
        {
            $where['title'] = ['LIKE', "%$param[keyword]%"];
        }

        if (!empty($startTime) && !empty($endTime))
        {
            $where['create_time'] = [['>= time', $startTime], ['<= time', $endTime]];
        }
        else
        {
            if (!empty($startTime))
            {
                $where['create_time'] = ['>= time', $startTime];
            }
            if (!empty($endTime))
            {
                $where['create_time'] = ['<= time', $endTime];
            }
        }

        $user_id = session('ADMIN_ID'); // 获取用户ID信息
        $user_role = Db::name('user')->where('id', $user_id)->field('authority,branch_id')->find();

        if ($user_role['authority'] == 'admin' || $user_role['authority'] == '管理员')
        {
            return $this->where($where)->with('category')->order('update_time', 'DESC')->paginate(10);
        }
        if ($user_role['authority'] == '总经理')
        {
            $postId = $this->getCategory($user_role['branch_id']);

            $where['post_id'] = ['in', $postId];
            return $this->where($where)->with('category')->order('update_time', 'DESC')->paginate(10);
        }
        if ($user_role['authority'] == '项目总监')
        {
            $where['post_id'] = $user_role['branch_id'];
            return $this->where($where)->with('category')->order('update_time', 'DESC')->paginate(10);
        }
        else
        {
            return null;
        }

    }
    /**
     * 链分类表
     */
    public function category()
    {
        return $this->belongsTo('PortalCategoryModel', 'post_id')->bind(['category_name' => 'name']);
    }

    /**
     * categories
     */
    public function categories()
    {
        return $this->belongsTo('PortalCategoryModel', 'post_id');
    }
    /**
     * 获取总经理板块下的所有文章数据
     * @param int $category_id 父级ID
     */
    private function getCategory($category_id)
    {
        $data = Db::name('portal_category')->where('parent_id', $category_id)->field(['id'])->select();
        $result = [];
        foreach ($data as $val)
        {
            $result[] = $val['id'];
        }
        return $result;
    }
}
